"""
Support module for portscanner.py to help calculate IP's.

This module sends an ARP Request for the network broadcast address
and stores the ip's that reply to it
"""
	
from scapy.all import srp,Ether,ARP,conf
conf.verb=0


class CalculateIp:
	"""
	Calculates the subnet IP and Netmask from the given IP and Netmask
	
	Keyword arguments:
    ip -- Host IP
    netmask -- Host Netmask
	"""
	def __init__(self,ip,netmask):
		"""Initializer for CalculateIP Class."""
		self.ip = ip
		self.mask = netmask
		self.ipList = []
		
	def get_net_size(self,mask2):
		"""Converts netmask from x.x.x.x to /x mode.
		
		Keyword arguments:
		mask2 -- Netmask to Convert
		
		"""
		binary_str=''
		for octet in mask2:
			binary_str += bin(int(octet))[2:].zfill(8)
		return str(len(binary_str.rstrip('0')))
	
	def calculate(self):
		"""Return IP's that respond to ARP Request"""
		ipaddr = self.ip.split('.')
		netmask = self.mask.split('.')
		net_start = [str(int(ipaddr[x]) & int(netmask[x])) for x in range(0,4)]
		add = '.'.join(net_start)+'/'+ self.get_net_size(netmask)
		ans, unans=srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=add),timeout=10,verbose=0)
		
		print "IP's that responded to ARP Request:"
		for snd,rcv in ans:
			x = rcv.sprintf(r"%ARP.psrc%")
			print x
			self.ipList.append(x)
		print '\n'
